<template>
  <form class="contact--form" @submit.prevent="handleSubmit">
    <div class="row">
      <div class="columns">
        <woot-avatar-uploader
          :label="$t('CONTACT_FORM.FORM.AVATAR.LABEL')"
          :src="avatarUrl"
          :username-avatar="name"
          :delete-avatar="!!avatarUrl"
          class="settings-item"
          @change="handleImageUpload"
          @onAvatarDelete="handleAvatarDelete"
        />
      </div>
    </div>
    <div class="row">
      <div class="columns">
        <label :class="{ error: $v.name.$error }">
          {{ $t('CONTACT_FORM.FORM.NAME.LABEL') }}
          <input
            v-model.trim="name"
            type="text"
            :placeholder="$t('CONTACT_FORM.FORM.NAME.PLACEHOLDER')"
            @input="$v.name.$touch"
          >
        </label>

        <label :class="{ error: $v.email.$error }">
          {{ $t('CONTACT_FORM.FORM.EMAIL_ADDRESS.LABEL') }}
          <input
            v-model.trim="email"
            type="text"
            :placeholder="$t('CONTACT_FORM.FORM.EMAIL_ADDRESS.PLACEHOLDER')"
            @input="$v.email.$touch"
          >
          <span v-if="$v.email.$error" class="message">
            {{ $t('CONTACT_FORM.FORM.EMAIL_ADDRESS.ERROR') }}
          </span>
        </label>
      </div>
    </div>
    <div class="medium-12 columns">
      <label :class="{ error: $v.description.$error }">
        {{ $t('CONTACT_FORM.FORM.BIO.LABEL') }}
        <textarea
          v-model.trim="description"
          type="text"
          :placeholder="$t('CONTACT_FORM.FORM.BIO.PLACEHOLDER')"
          @input="$v.description.$touch"
        />
      </label>
    </div>
    <div class="row">
      <div class="medium-12 columns">
        <label :class="{ error: $v.phoneNumber.$error }">
          {{ $t('CONTACT_FORM.FORM.PHONE_NUMBER.LABEL') }}
          <input
            v-model.trim="phoneNumber"
            type="text"
            :placeholder="$t('CONTACT_FORM.FORM.PHONE_NUMBER.PLACEHOLDER')"
            @input="$v.phoneNumber.$touch"
          >
          <span v-if="$v.phoneNumber.$error" class="message">
            {{ $t('CONTACT_FORM.FORM.PHONE_NUMBER.ERROR') }}
          </span>
        </label>
        <div
          v-if="$v.phoneNumber.$error || !phoneNumber"
          class="callout small warning"
        >
          {{ $t('CONTACT_FORM.FORM.PHONE_NUMBER.HELP') }}
        </div>
      </div>
    </div>
    <woot-input
      v-model.trim="companyName"
      class="columns"
      :label="$t('CONTACT_FORM.FORM.COMPANY_NAME.LABEL')"
      :placeholder="$t('CONTACT_FORM.FORM.COMPANY_NAME.PLACEHOLDER')"
    />
    <div class="medium-12 columns">
      <label>
        Social Profiles
      </label>
      <div
        v-for="socialProfile in socialProfileKeys"
        :key="socialProfile.key"
        class="input-group"
      >
        <span class="input-group-label">{{ socialProfile.prefixURL }}</span>
        <input
          v-model="socialProfileUserNames[socialProfile.key]"
          class="input-group-field"
          type="text"
        >
      </div>
    </div>
    <div class="modal-footer">
      <div class="medium-12 columns">
        <woot-submit-button
          :loading="inProgress"
          :button-text="$t('CONTACT_FORM.FORM.SUBMIT')"
        />
        <button class="button clear" @click.prevent="onCancel">
          {{ $t('CONTACT_FORM.FORM.CANCEL') }}
        </button>
      </div>
    </div>
  </form>
</template>

<script>
import alertMixin from '@/yichat.web.share/mixins/alertMixin'
import {
  DuplicateContactException,
  ExceptionWithMessage,
} from '@/yichat.web.share/helpers/CustomErrors'
import { required, email } from 'vuelidate/lib/validators'

import { isPhoneE164OrEmpty } from '@/yichat.web.share/helpers/Validators'

export default {
  mixins: [alertMixin],
  props: {
    contact: {
      type: Object,
      default: () => ({}),
    },
    inProgress: {
      type: Boolean,
      default: false,
    },
    onSubmit: {
      type: Function,
      default: () => {},
    },
  },
  data () {
    return {
      companyName: '',
      description: '',
      email: '',
      name: '',
      phoneNumber: '',
      avatarFile: null,
      avatarUrl: '',
      socialProfileUserNames: {
        facebook: '',
        twitter: '',
        linkedin: '',
        github: '',
      },
      socialProfileKeys: [
        { key: 'facebook', prefixURL: 'https://facebook.com/' },
        { key: 'twitter', prefixURL: 'https://twitter.com/' },
        { key: 'linkedin', prefixURL: 'https://linkedin.com/' },
        { key: 'github', prefixURL: 'https://github.com/' },
      ],
    }
  },
  validations: {
    name: {
      required,
    },
    description: {},
    email: {
      email,
    },
    companyName: {},
    phoneNumber: {
      isPhoneE164OrEmpty,
    },
    bio: {},
  },

  watch: {
    contact () {
      this.setContactObject()
    },
  },
  mounted () {
    this.setContactObject()
  },
  methods: {
    onCancel () {
      this.$emit('cancel')
    },
    onSuccess () {
      this.$emit('success')
    },
    setContactObject () {
      const {
        email: emailAddress,
        phoneNumber: phoneNumber,
        name,
      } = this.contact
      const additionalAttributes = this.contact.additionalAttributes || {}

      this.name = name || ''
      this.email = emailAddress || ''
      this.phoneNumber = phoneNumber || ''
      this.companyName = additionalAttributes.companyName || ''
      this.description = additionalAttributes.description || ''
      this.avatarUrl = this.contact.thumbnail || ''
      const {
        socialProfiles: socialProfiles = {},
        screen_name: twitterScreenName,
      } = additionalAttributes
      this.socialProfileUserNames = {
        twitter: socialProfiles.twitter || twitterScreenName || '',
        facebook: socialProfiles.facebook || '',
        linkedin: socialProfiles.linkedin || '',
        github: socialProfiles.github || '',
      }
    },
    getContactObject () {
      const contactObject = {
        id: this.contact.id,
        name: this.name,
        email: this.email,
        phoneNumber: this.phoneNumber,
        additionalAttributes: {
          ...this.contact.additionalAttributes,
          description: this.description,
          companyName: this.companyName,
          socialProfiles: this.socialProfileUserNames,
        },
      }
      if (this.avatarFile) {
        contactObject.avatar = this.avatarFile
        contactObject.isFormData = true
      }
      return contactObject
    },
    async handleSubmit () {
      this.$v.$touch()

      if (this.$v.$invalid) {
        return
      }
      try {
        await this.onSubmit(this.getContactObject())
        this.onSuccess()
        this.showAlert(this.$t('CONTACT_FORM.SUCCESS_MESSAGE'))
      } catch (error) {
        if (error instanceof DuplicateContactException) {
          if (error.data.includes('email')) {
            this.showAlert(
              this.$t('CONTACT_FORM.FORM.EMAIL_ADDRESS.DUPLICATE')
            )
          } else if (error.data.includes('phoneNumber')) {
            this.showAlert(this.$t('CONTACT_FORM.FORM.PHONE_NUMBER.DUPLICATE'))
          }
        } else if (error instanceof ExceptionWithMessage) {
          this.showAlert(error.data)
        } else {
          this.showAlert(this.$t('CONTACT_FORM.ERROR_MESSAGE'))
        }
      }
    },
    handleImageUpload ({ file, url }) {
      this.avatarFile = file
      this.avatarUrl = url
    },
    async handleAvatarDelete () {
      try {
        if (this.contact && this.contact.id) {
          await this.$store.dispatch('contacts/deleteAvatar', this.contact.id)
          this.showAlert(
            this.$t('CONTACT_FORM.DELETE_AVATAR.API.SUCCESS_MESSAGE')
          )
        }
        this.avatarFile = null
        this.avatarUrl = ''
      } catch (error) {
        this.showAlert(
          error.message
            ? error.message
            : this.$t('CONTACT_FORM.DELETE_AVATAR.API.ERROR_MESSAGE')
        )
      }
    },
  },
}
</script>

<style scoped lang="scss">
.contact--form {
  padding: var(--space-normal) var(--space-large) var(--space-large);

  .columns {
    padding: 0 var(--space-smaller);
  }
}

.input-group-label {
  font-size: var(--font-size-small);
}
</style>
